<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/28 0028
 * Time: 11:58
 */

namespace App\Server;


use App\Model\KeyWord;
use App\Model\Rule;
use Houdunwang\WeChat\WeChat;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;

class WechatServer
{
    public function __construct()
    {

    }

    public function link()
    {
        $config = hd_config('wechat');
        WeChat::config($config);
        WeChat::valid();
    }

    //定义一个方法，帮助加载模板，加载消息回复中创建规则和关键得公共部分
    public function ruleKey($id = 0)
    {
        $rul = Rule::findOrNew($id);
//            dd($rul->toArray());
        $oldRul = [
            'id' => $id,
            'name' => $rul->name,
            'keywords' => $rul->keyWord
        ];
//           $newRul=$oldRul['keywords'];
//           dd($newRul);
        return view('wechat.wxReply.common', compact('oldRul'));
    }

    //保存规则和关键词
    public function storeKey($data)
    {
        Validator::make($data, [
            'name' => 'required',
        ], [
            'name.required' => '规则名称不能为空',
        ])->validate();
        $post=$data['rule'];
        $newpost=json_decode($post,true);
        Validator::make($newpost, [
            'keywords' => 'required',
        ], [
            'keywords.required' => '关键词不能为空',
        ])->validate();
        $rul = Rule::findOrNew($newpost['id']);
        $rul->name = $data['name'];
        $rul->save();
                $rul->keyWord()->delete();
        foreach ($newpost['keywords'] as $keyword){
            $rul->keyWord()->create($keyword);
        }
        return $rul;
    }
}